package com.easylinkin.linkappapi.wxminiapp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * 微信相关Controller
 * 
 * @author OYGD
 *
 */
@Slf4j
@RestController
public class WeChatController {

	RestTemplate restTemplate = new RestTemplate();

	@Value("${wxminiapp.appid}")
	String appid;

	@Value("${wxminiapp.appsecret}")
	String secret;
	
	/**
	 * 微信小程序接口可以不用登录
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/anon/wechat/jscode2session")
	public RestMessage jscode2session(@RequestParam("jsCode") String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={jsCode}&grant_type=authorization_code";

		String text = restTemplate.getForObject(url, String.class, appid, secret, code);
		JSONObject resp = JSON.parseObject(text);
//		resp.getString("openid");
		String sessionKey = resp.getString("session_key");
//		resp.getString("unionid");
		String errcode = resp.getString("errcode");
		String errmsg = resp.getString("errmsg");
		if (StringUtils.isNoneBlank(errmsg)) {
			throw new RuntimeException(String.format("请求微信接口失败 code: %s, msg: %s", errcode, errmsg));
		}

		JSONObject result = new JSONObject();
		String encrypt = WeChatUtil.encryptSessionKey(sessionKey);
		result.put("sessionKey", encrypt);

		return RestBuilders.successBuilder().data(result).build();
	}
	
//	@PostMapping("/miniappLogin")
//	public RestMessage miniappLogin(@RequestBody WechatAppToken token) {
//		
//		String sessionKey = token.getSessionKey();
//
//		String decoded = null;
//		JSONObject decodedObj = null;
//		String decryptSessionKey = WeChatUtil.decryptSessionKey(sessionKey);
//		if(null == decryptSessionKey) {
//			throw new IllegalArgumentException("sessionKey错误");
//		}
//		try {
//			decoded = WeChatUtil.decrypt(token.getEncryptedData(), decryptSessionKey, token.getIv());
//			decodedObj = JSON.parseObject(decoded);
//		} catch (Exception e) {
//			log.warn(e.getMessage() , e);
//			throw new IllegalArgumentException("解密失败" + e.getMessage(), e);
//		}
//		
//		JSONObject watermark = decodedObj.getJSONObject("watermark");
//		if (watermark == null || !StringUtils.equals(appid, watermark.getString("appid"))) {
//			log.warn(decoded);
//			throw new IllegalArgumentException("appid校验失败");
//		}
//		
//		String phone = decodedObj.getString("phoneNumber");
//		// 进行登录处理
////		User user = userService.getUserByTel(phone);
////        if (user == null) {
////		return RestBuilders.failureBuilder().message("用户不存在").build();
////        }
//        
//		JSONObject json = new JSONObject();
//		json.put("token", ""); //  登录成功后把sessionId返回
//		return RestBuilders.successBuilder().data(json).build();
//	}

}
